package com.github.baichuan.web.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.util.Optional;

public class BearerToken {
    public static Optional<String> get(HttpServletRequest request){
        String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
        if(StringUtils.isBlank(authorization)){
            return Optional.empty();
        }
        return Optional.of(parse(authorization));
    }

    public static Optional<String> get(ServerHttpRequest request){
        String authorization = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if(StringUtils.isBlank(authorization)){
            return Optional.empty();
        }
        return Optional.of(parse(authorization));
    }

    public static String parse(String authorization){
        String[] spans = authorization.split(" ");
        if(spans.length != 2) {
            throw new RuntimeException("Bearer Token must be split with blank");
        }
        if(!spans[0].equals("Bearer")) {
            throw new RuntimeException("Bearer Token must start with Bearer");
        }
        return spans[1];
    }
}
